﻿// **************************
// JQuery function and fixes:
// ***************************
// Fix the jQuery fade for IExplorer.
jQuery.fn.fadeTo = function (speed, to, callback) {
    return this.animate({ opacity: to }, speed, function () {
        if (to == 1 && jQuery.browser.msie)
            this.style.removeAttribute('filter');
        if (jQuery.isFunction(callback))
            callback();
    });
};

        
// *************************************
// HTML Select (dropdown menu) functions:
// *************************************

// Function called to populate an select with all the values of a certain type of entity; if selectValue is given, select the element with its value; it callback is given and is 
// a function, call it at the end.
function populateSelect(entity, selectValue, callback) {
    var waitingId = entity + 'SelectWaiting';
    turnOnWaiting(waitingId);
    var select = $('#' + entity + 'Id');
    $.post(approot + '/' + entity + '/GetAll/', {},
        function (data) {
            populateSelectOnComplete(select, data, selectValue);
            turnOffWaiting(waitingId);
            if (jQuery.isFunction(callback)) callback();
        }
    );
}
//Called on the completion of the AJAX call asking for the select elements. Populate a dropdown 'select' with values from 'data', a list of objects with "Id" and "Name"; 
// if 'selectValue' is passed and >0, select the item with Id == selectValue;
function populateSelectOnComplete(select, data, selectValue) {
    select.html('');
    $.each(data, function (id, option) {
        select.append($('<option></option>').val(option.Id).html(option.Name));
    });
    if (selectValue > 0) {
        select.val(selectValue).attr('selected', 'selected');
    }
}

function populateMunicipalitySelect(stateId, selectValue) {
    var waitingId = 'MunicipalitySelectWaiting';
    turnOnWaiting(waitingId);
    var select = $('#MunicipalityId');
    $.post(approot + '/Municipality/GetFromState/', {state:stateId},
        function (data) {
            populateSelectOnComplete(select, data, selectValue);
            turnOffWaiting(waitingId);
        }
    );
}
//**************************
// AJAX creation of entities
//**************************

// SHOW and FADE functions: functions to hide, show and fade in/out differents forms, used when there are multiple ajax forms on the same page, allowing the user to perform
// edit/insert operations on different entities. For instance, when creating a new author, if the user wants to create a new institution for him, he can use this AJAX 
// to do it on the same page; the author form fades out, and the institution form is shown. When the new institution is created, the institution form is hidden. Then, calling the
// function to populate the select, the new institution is added to the select combobox and it is also selected. 

// function fade: Fades an entity form. Fade In if bool = true, Fade Out otherwise. Also En(dis)able the submit button of the form.
// The Id of the div containing the form must be in the format <Entity>Form, and the id of the submit button <Entity>Submit. For instance,
// <div id="AuthorForm"> and <input type="submit id="AuthorSubmit">.
function fade(entity, bool, callback) {
    $("#" + entity + "Submit").attr("disabled", bool);
    var opacity = 0.3;
    if (!bool) opacity = 1;
    $("#" + entity + "Form").fadeTo('slow', opacity, callback);
}

// shows a new form for 'entity1', fading out the current form for 'entity2' and disabling its submit button.
function showAndFadeOut(entity1, entity2) {
    var formId = "#" + entity1 + "Form";
    $(formId).show('slow');
    fade(entity2, true, function () {
        // scroll to the form:
        var destination = $(formId).offset().top;
        $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination - 20 }, 'slow');
        return false;
    });
}
// hides the current form for 'entity1' (operation succesfull or canceled by user), fading in the form for 'entity2' and enabling its submit button.
function hideAndFadeIn(entity1, entity2) {
    $("#" + entity1 + "Form").hide('slow');
    fade(entity2, false);
}

// Turn waiting on, when some AJAX operation is happening. Shows the div where the "waiting" image is hidden and also changes the cursor.
function turnOnWaiting(id) {
    document.body.style.cursor = 'wait';
    //$("#" + id).css("visibility", "visible");
    $("#" + id).show();
}
// Turn waiting off, when the AJAX operation is completed. Hides the div where the "waiting" image is hidden and also changes the cursor back to default.
function turnOffWaiting(id) {
    document.body.style.cursor = 'default';
    //$("#" + id).css("visibility", "hidden");
    $("#" + id).hide();
}

function OnCompleteCreate(content, entity, parentEntity, callback) {
    var result = eval('(' + content.get_data() + ')');
    if (result.Success) {
        InformationMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
        if (parentEntity != null) hideAndFadeIn(entity, parentEntity);
        if (entity != null) populateSelect(entity, result.Data.Id, callback);
    }
    else {
        ErrorMessage('<b>' + result.Header + "</b><br>" + result.Message, result.Seconds);
    }
}

/*
AUTO COMPLETE
*/
//Autocomplete setup: adds autocomplete in a textbox. 
function addAutoComplete(entity, callback) {
    $("input#" + entity + "AutoComplete").autocomplete({
        source: approot + "/" + entity + "/AutoComplete",
        delay: 200,
        select: function (event, ui) { 
            $("input#" + entity + "AutoComplete").val(ui.item.value); 
            if (jQuery.isFunction(callback)) { 
                callback(event,ui); 
                return false;
            } else return true;
        }
    });
}

/* 
************
SHOW DETAILS
************

Functions to show a jquery ui dialog box with the result of a ajax query for some entity details. The updatedivid must be "<entity>Details", and the Ajax form id must be "<entity>DetailsAjaxForm". 
Also there must be a hidden field with id = 'id': <%: Html.Hidden("id")%>, that will receive the id of the entity to get the details from.

*/
//Little hack to enable ajaxform submit in the javascript; the trick is to call the onsubmit also
//$("document").ready(function () {
    //update: apparently is causing to submit twice in firefox; it works without it, so only execute on other browsers; tested on IE and Chrome, both need it otherwise they submit without AJAX
    //update2: actually it causes double submit on ALL browsers, on scenarios activated by the submit button; the fix
    // is to add the following line only in the scenarios where the AJAX call is made by javascript, not clicking on the submit button (like the DETAILS popup)
    //if(!$.browser.mozilla) $("form").submit(function (event) { eval($(this).attr("onsubmit")); return false; });
//});
function showDetails(entity) {
     var dialogId = "#" + entity + "Details";
     $(dialogId).dialog({ width: 700, position: "center", buttons: { "Ok": function () { $(this).dialog("close"); } } });
}
function requestDetails(entity, id) {
    //update the hiddend id (it is the same id for every entity)
    $("#id").val(id);
    //post the ajax that retrieves the details, put the result in the 'details' div and calls showDetails on success;
    $("#" + entity + "DetailsAjaxForm").submit();
}

function requestDelete(entity, id) {
    //update the hiddend id (it is the same id for every entity)
    $("#deleteId").val(id);
    //post the ajax that delete
    $("#" + entity + "DeleteAjaxForm").submit();
}

function OnAjaxFailure() {
    $("#AjaxError").html("<div class='ui-state-error'><p>AJAX request error</p></div>");
    $("#AjaxError").dialog({ width: 700, position: "center", buttons: { "Ok": function () { $(this).dialog("close"); } } });
}

function blockUI() {
    $.blockUI({
        message: $('#MainWaiting'), //'<h1>Wait....</h1>', 
        showOverlay: false,
        css: {
            top: ($(window).height() - 30) / 2 + 'px',
            left: ($(window).width() - 30) / 2 + 'px',
            width: '30px'
        }
    });
    //$.unblockUI(); //to unblock;
}
//* Functions to include and remove words in a dynamic list. Words are added calling AddWord(), passing the word and the string with the name of the array in the original scope.
// This string is also the id of the html item (a <span> or <div> for instance) where to display the list of current words and store the hidden inputs with these words. 
// It is also the name of the hidden input used to submit the words, 
// i.e, <input type="hidden" name="<string_with_id>" value="<list of words" >

// You need to create an array for storing keywords, usually name like the entity: like this:
// var Keyword = new Array();
// and then add words calling:
// AddWord("Your word", "Keyword"); -> word to add, name of the array
// You can have multiple lists, giving different arrays with different ids:
// var Keyword = new Array();
// var Author = new array();
// AddWord("Genetics", "Keyword");
// AddWord("Watson Creek", "Author");
// When the user POSTs, Words are received as a comma-separated string; 

// START:
//Preload "DELETE WORD" image:
var pic = new Image(16, 16);
pic.src = approot + "/Content/img/delete.png";
// helper functions to add/remove keywords from TextBox or Select:
function addWordFromTextBox(entity) {
    var box = document.getElementById(entity + 'AutoComplete'); //Textbox naming convention, entity + 'AutoComplete'
    AddWord(box.value, entity);
    box.value = '';
}
function addWordFromSelect(entity) {
    var selected = $('#' + entity + 'Id option:selected').text();
    AddWord(selected, entity);
}

function AddWord(word, entity) {
    if (word == "") return;
    var id = entity + 'Field'; //convention for the id of div displaying the list: entity + 'Field'
    var array = eval(id);
    if (!IsInArray(array, word)) {
        array.push(word);
        UpdateDivAndHidden(array, id);
    }
}
function RemoveWord(idx, array, id) {
    array.splice(idx, 1);
    UpdateDivAndHidden(array, id);
}
function UpdateDivAndHidden(array, id) {
    var str = "";
    var hidden = "";
    for (var i = 0; i < array.length; i++) {
        var key = array[i];
        // DIV with keywords:
        str = str + "<span class='white round label'>" + key + "</span> <a href=\"javascript:RemoveWord(" + i + "," + id + ", '" + id + "');\"><img src='" + pic.src + "'></a>";
        if (i < array.length - 1) str = str + ", ";
        // HIDDEN:
        hidden = hidden + "<input type='hidden' name='" + id + "' value='" + key + "'>";
    }
    document.getElementById(id).innerHTML = str + hidden; //  "<input type='hidden' name='" + id + "' value='" + array.toString() + "'>"; // hidden;
}

function IsInArray(array, word) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == word) return true
    }
    return false;
}
